/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: UseFunction.java   2020-09-30 17-36-59
 * Author: Evan
 */
package cn.datacare.orm.engine.function;

import cn.datacare.orm.manager.impl.SQLManager;
import cn.datacare.orm.source.SQLResult;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

import static cn.datacare.orm.constant.Constants.PARAM_MANAGER;
import static cn.datacare.orm.constant.Constants.PARAM_PARAMS;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-09-30 17-36-59
 * @since V1.0
 */
public class UseFunction extends AbstractFunction implements Function {
    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(UseFunction.class);

    @Override
    public Object call(Object[] paras, Context ctx) {
        SQLManager sm = (SQLManager) ctx.getGlobal(PARAM_MANAGER);
        // 保留，免得被覆盖
        SQLResult result = this.getSqlResult(sm, ctx, paras);
        List list = (List) ctx.getGlobal(PARAM_PARAMS);
        //追加参数
        list.addAll(result.getJdbcParam());
        ctx.set(PARAM_PARAMS, list);
        try {
            ctx.byteWriter.writeString(result.getJdbcSql());
        } catch (IOException e) {
            log.warn(e.getMessage(), e);
        }
        return null;
    }
}
